﻿using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.WorksheetElements
{
    [XmlRoot("sheetData", Namespace = Constants.ExcelMain)]
    public class Sheetdata : XmlSerializable
    {
        [XmlElement("row", Namespace = Constants.ExcelMain)]
        public XmlList<Row> Rows { get; set; }

        [XmlIgnore]
        public bool RowsSpecific { get { return Rows.Count > 0; } }

        [XmlIgnore]
        public Row this[int i]
        {
            get
            {
                Row row = Rows.FirstOrDefault(r => r.Index == (uint)i);
                if (row != null)
                {
                    return row;
                }

                if (Rows.Count > i)
                {
                    return Rows[i];
                }

                throw new IndexOutOfRangeException();
            }
            set
            {
                Row row = Rows.FirstOrDefault(r => r.Index == (uint)i);
                if (row != null)
                {
                    row.Copy(value);
                }
                else if (Rows.Count > i)
                {
                    Rows[i].Copy(value);
                }
                else
                {
                    throw new IndexOutOfRangeException();
                }
            }
        }

        public Sheetdata()
        {
            Rows = new XmlList<Row>();
        }

        public Row AddRow()
        {
            Row r = new Row();
            Rows.Add(r);
            return r;
        }

        public Row CreateRow(uint index)
        {
            Row r = new Row();
            r.Index = index;
            Rows.Add(r);
            Rows.Sort(delegate(Row r1, Row r2)
            {
                uint r1i = r1.Index == null ? (uint)Rows.IndexOf(r1) : r1.Index.Value;
                uint r2i = r2.Index == null ? (uint)Rows.IndexOf(r2) : r2.Index.Value;
                if (r1i < r2i) return -1;
                if (r1i == r2i) return 0;
                return 1;
            });
            return r;
        }

        public Cell CreateCell(uint rowIndex, uint columnIndex)
        {
            Row row = Rows.FirstOrDefault(r => r.Index == rowIndex);
            if (row == null)
            {
                row = CreateRow(rowIndex);
            }
            return row.CreateCell(columnIndex);
        }
    }
}
